package com.sora.eduservice.controller;


import com.sora.commonutils.R;
import com.sora.commonutils.exceptionhandler.GuliException;
import com.sora.eduservice.client.VodClient;
import com.sora.eduservice.entity.EduVideo;
import com.sora.eduservice.service.EduVideoService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;

/**
 * <p>
 * 课程视频 前端控制器
 * </p>
 *
 * @author sora
 * @since 2022-12-28
 */
@RestController
@RequestMapping("/eduservice/video")
@CrossOrigin
public class EduVideoController {
    @Autowired
    private EduVideoService eduVideoService;
    @Autowired
    private VodClient vodClient;
    /**
     * 添加视频
     * @param eduVideo
     * @return
     */
    @PostMapping("addVideo")
    public R addVideo(@RequestBody EduVideo eduVideo) {
        eduVideoService.save(eduVideo);
        return R.ok();
    }

    /**
     * 删除数据库视频和阿里云的视频
     * @param id
     * @return
     */
    @DeleteMapping("{id}")
    public R deleteVideo(@PathVariable String id) {
        EduVideo video = eduVideoService.getById(id);
        String sourceId = video.getVideoSourceId();
        if (!StringUtils.isEmpty(sourceId)) {
            System.out.println(sourceId);
            R res = vodClient.removeAliyunVideoById(sourceId);
            if (res.getCode() == 20001) {
                throw new GuliException(20001,"删除视频失败，熔断器。。。");
            }
        }
        eduVideoService.removeById(id);
        return R.ok();
    }

    /**
     * 删除整个课程的视频
     * @param id
     * @return
     */
    @DeleteMapping("deleteCourseVideo/{id}")
    public R deleteCourseVideo(@PathVariable String id) {
        eduVideoService.removeVideoByCourseId(id);
        return R.ok();
    }
    /**
     * 更新视频
     * @param eduVideo
     * @return
     */
    @PostMapping("updateVideo")
    public R updateVideo(@RequestBody EduVideo eduVideo) {
        eduVideoService.updateById(eduVideo);
        return R.ok();
    }

    /**
     * 获取视频
     * @param videoId
     * @return
     */
    @GetMapping("getVideoById/{videoId}")
    public R getVideoById(@PathVariable String videoId) {
        EduVideo video = eduVideoService.getById(videoId);
        return R.ok().data("video",video);
    }
}

